﻿using CPPEI.ETL.DataServiceInterface;
using CPPEI.ETL.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CPPEI.ETL.Infrastructure;
using ENT = CPPEI.ETL.Domain.Entities;
using MOD = CPPEI.ETL.Domain.Models;

namespace CPPEI.ETL.DSImplement
{
    public class ExcelDtSerManager : IDtSerManager
    {
        public ServiceResult<CPPEI.ETL.Domain.Entities.DtSer> CreateDataService(EtlDbContext dbContext, string userId, Guid folderId, string name, string address, bool needAuth,
            string authUser,
            string authPassword,
            Guid categoryId,
            Guid typeId,
            string description)
        {
            #region
            ENT.DtSerType dtSerType = null;//GetDtSerType(CPPEI.ETL.Domain.Cache.DtSerCategoryList, opParams.TypeId);

            foreach (var category in CPPEI.ETL.Domain.Cache.DtSerCategoryList)
            {
                if (category.Id == categoryId)
                {
                    foreach (var type in category.TypeList)
                    {
                        if (type.Id == typeId)
                        {
                            dtSerType = type;
                            break;
                        }
                    }
                }
            }
            #endregion

            if (dtSerType == null)
            {
                return new ServiceResult<CPPEI.ETL.Domain.Entities.DtSer>(false, ErrorCode.DtSerTypeNotFound, "invalid parameter");
            }
            else
            {
                WSDataServiceProxy proxy = new WSDataServiceProxy();
                if (proxy == null)
                {
                    return new ServiceResult<CPPEI.ETL.Domain.Entities.DtSer>(false, ErrorCode.DtSerProxyNotFound, "invalid parameter");
                }
                else
                {
                    //TDataService dtSerSchema = proxy.GetSchema(new DataServiceInfo(address, needAuth, authUser, authPassword));

                    DateTime now = DateTime.Now;

                    EntityRepository<ENT.DtSer> serRep = new EntityRepository<ENT.DtSer>(dbContext);

                    ENT.DtSer dtSer = new ENT.DtSer();
                    dtSer.Id = Guid.NewGuid();
                    dtSer.Name = name;
                    dtSer.Address = "";
                    dtSer.CategoryId = categoryId;
                    dtSer.TypeId = typeId;
                    dtSer.NeedAuth = needAuth;
                    dtSer.AuthUser = authUser;
                    dtSer.AuthPassword = CEncoder.Encode(authPassword);//加密 2017-01-17 
                    dtSer.Creator = userId;
                    dtSer.CreatedTime = now;
                    dtSer.IsDeleted = false;
                    dtSer.IsEnabled = true;
                    dtSer.Description = description;
                    dtSer.FolderId = folderId;
                    serRep.Create(dtSer);
                    return new ServiceResult<CPPEI.ETL.Domain.Entities.DtSer>(true, ErrorCode.COM_NoError, string.Empty, dtSer);
                }
            }
        }

        public ServiceResult CreateDataSource(EtlDbContext dbContext, string userId, Guid dtSerId, string name, string value, int type, string parameterSettings, string columnSettings, string settings)
        {
            // 验证列信息是否合格
            if (string.IsNullOrEmpty(columnSettings))
            {
                return new ServiceResult(false, ErrorCode.COM_Exception, "列信息有错误");
            }

            string[] columnSegments = columnSettings.Split(new char[] { ',' });
            for (int index = 0; index < columnSegments.Length; index+=3)
            {
                string colName = columnSegments[index];
                //格式应该为xx:xx
                string[] colNameArr = colName.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                if(colNameArr.Length != 2)
                {
                    return new ServiceResult(false, ErrorCode.COM_Exception, string.Format("列{0}名称格式不符合要求", colName));
                }
                else
                {
                    if(!IsName(colNameArr[0]) || !IsName(colNameArr[1]))
                    {
                        return new ServiceResult(false, ErrorCode.COM_Exception, string.Format("列{0}名称格式不符合要求", colName));
                    }
                }

            }
            DateTime now = DateTime.Now;

            EntityRepository<ENT.DtSer> serRep = new EntityRepository<ENT.DtSer>(dbContext);
            EntityRepository<ENT.DtSource> sourceRep = new EntityRepository<ENT.DtSource>(dbContext);
            EntityRepository<ENT.EDtSourceParameter> pRep = new EntityRepository<ENT.EDtSourceParameter>(dbContext);
            EntityRepository<ENT.EDtSourceColumn> cRep = new EntityRepository<ENT.EDtSourceColumn>(dbContext);

            ENT.DtSource dtSource = new ENT.DtSource();
            dtSource.Id = Guid.NewGuid();
            dtSource.Name = name;
            dtSource.Value = value;
            dtSource.Type = DEF.ExcelSourceType.Sheet;
            dtSource.Creator = userId;
            dtSource.CreatedTime = now;
            dtSource.DtSerId = dtSerId;
            dtSource.Settings = settings;
            sourceRep.Create(dtSource);

            // insert data source parameters
            string[] parameterSegments = parameterSettings.Split(new char[] { ',' });
            for (int index = 0; index < parameterSegments.Length; index += 4)
            {
                ENT.EDtSourceParameter eParameter = new ENT.EDtSourceParameter();
                eParameter.Id = Guid.NewGuid();
                eParameter.DataType = parameterSegments[index + 1];
                eParameter.DtSerId = dtSerId;
                eParameter.DtSourceId = dtSource.Id;
                eParameter.Name = parameterSegments[index];
                eParameter.DefaultValue = parameterSegments[index + 2];
                eParameter.Description = parameterSegments[index + 3];
                eParameter.Index = index / 4;
                pRep.Create(eParameter);
            }

            // insert data source columns
            for (int index = 0; index < columnSegments.Length; index += 3)
            {
                ENT.EDtSourceColumn eColumn = new ENT.EDtSourceColumn();
                eColumn.Id = Guid.NewGuid();
                eColumn.DataType = columnSegments[index + 1];
                eColumn.DtSerId = dtSerId;
                eColumn.DtSourceId = dtSource.Id;
                eColumn.Name = columnSegments[index];
                eColumn.Description = columnSegments[index + 2];
                eColumn.Index = index / 3;
                cRep.Create(eColumn);
            }

            return new ServiceResult(true, ErrorCode.COM_NoError, string.Empty);
        }

        public bool CanCreateDataSource()
        {
            return true;
        }

        public List<string> EnumerateDataSource(string address, bool needAuth, string authUser, string authPassword)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 字母开头，字母数字_组成的格式
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private static bool IsName(string name)
        {
            Regex regex = new Regex(@"^[a-zA-Z][a-zA-z0-9_]*$");
            if (regex.IsMatch(name))
            {
                return true;
            }
            return false;
        }
    }
}
